package com.x.uikit.toolbar;

import android.content.Context;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;

import com.x.uikit.link.XLink;
import com.x.uikit.link.XParams;

public class XToolbarItem extends FrameLayout implements XLink.CommandHandler {
    @NonNull
    protected String mToken;
    @NonNull
    protected IClickListener mClickListener;
    protected XLink.EventObserver mEventObserver;

    public XToolbarItem(@NonNull Context context, @NonNull String token) {
        super(context);
        mToken = token;
        if (!customClickListener()) {
            setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mClickListener.onClick(XToolbarItem.this);
                }
            });
            setOnLongClickListener(v -> {
                mClickListener.onLongClick(XToolbarItem.this);
                return true;
            });
        }
    }

    /**
     * 如果子类想自定义item的点击事件，可以重新这个方法，返回true
     * 或者重新设置setOnClickListener、setOnLongClickListener
     *
     * @return true 自定义 false 使用默认实现
     */
    protected boolean customClickListener() {
        return false;
    }

    public final void setItemClickListener(@NonNull IClickListener listener) {
        mClickListener = listener;
    }

    @Override
    public boolean handCommand(int commandId, XParams params, XParams result) {
        return false;
    }

    public void setEventObserver(XLink.EventObserver observer) {
        mEventObserver = observer;
    }

    public void sendEvent(int eventId) {
        sendEvent(eventId, null, null);
    }

    public void sendEvent(int eventId, XParams params) {
        sendEvent(eventId, params, null);
    }

    public void sendEvent(int eventId, XParams params, XParams result) {
        if (mEventObserver != null) {
            mEventObserver.onEvent(eventId, params, result);
        }
    }

    public void setItemSelected(boolean selected) {

    }

    /**
     * @param progress 0-1
     */
    public void setItemSelectedProgress(float progress) {

    }

    public interface IClickListener {
        void onClick(XToolbarItem item);

        void onLongClick(XToolbarItem item);
    }
}
